package Servlet;

import Utils.DbUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

@WebServlet("/addTableServlet")
public class addTableServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String tableName = req.getParameter("tableName");
        String[] columnNames = req.getParameterValues("columnName");
        String[] dataType = req.getParameterValues("dataType");
        String[] length = req.getParameterValues("length");
        String[] isNull = req.getParameterValues("isNull");
        String[] Primarykey = req.getParameterValues("Primarykey");
        String sql = "CREATE TABLE " + tableName + " (";
        for (int i = 0; i < columnNames.length; i++) {
            sql += columnNames[i] + " " + dataType[i] + "(" + length[i] + ")" + " " + isNull[i];
            if (Primarykey[i].equals("is")) {
                if (i == columnNames.length - 1) {
                    sql += " " + "PRIMARY KEY";
                } else {
                    sql += " " + "PRIMARY KEY,";
                }
            } else {
                if (i != columnNames.length - 1) {
                    sql += ",";
                }
            }
        }
        sql += ")";
        System.out.println(sql);
        Connection connection = null;
        try {
            connection = DbUtil.getConnection(req);
            Statement stmt = connection.createStatement();
            stmt.executeUpdate(sql);
            DbUtil.close(connection, null, null);
            resp.sendRedirect("GetAllTableServlet");
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    @Override
    public void destroy() {
        super.destroy();
    }

    @Override
    public void init() throws ServletException {
        super.init();
    }
}
